package com.example.demo01.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.setting.dialect.Props;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangxun
 */
@Slf4j
public class PropertiesUtil {

    public static ConcurrentHashMap<String, Properties> concurrentHashMap = new ConcurrentHashMap(32);

    public static Properties readPropertiesFile(String filePath) throws IOException {
        Properties srcProperty = concurrentHashMap.get(filePath);
        if (srcProperty == null) {
            Properties properties = loadProperties(filePath);
            if (properties != null && filePath != null) {
                concurrentHashMap.put(filePath, properties);
                return properties;
            } else {
                log.error("PropertiesUtil properties:[{}] filePath:[{}]", properties.toString(), filePath);
                throw new IOException("PropertiesUtil properties is null or  filePath:is null");
            }
        } else {
            return srcProperty;
        }
    }

    private static synchronized Properties loadProperties(String filePath) {
        InputStream inputStream = null;

        Properties props = new Properties();
        try {
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            inputStream = classPathResource.getInputStream();
            props.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            return props;
        } catch (Exception e) {
            log.error("PropertiesUtil error ----------------加载文件异常", e);
            e.printStackTrace();
        } finally {
            IoUtil.close(inputStream);
        }
        return null;
    }

    private static synchronized Properties loadProperties2(String filePath) {
        return new Props(filePath);
    }
}
